package com.lanyanhua.flow;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WeChatFlowTest
 * @Description:TODO ()
 * @author: lanyanhua
 * @date: 2020/10/14 1:51 下午
 * @Copyright:
 */
public class WeChatFlowTest {

    //企业ID
    private final static String id = "ww7f42114febf9659e";
    //审批应用ID
    private final static String agentId = "3010040";
    //审批应用Secret
    private final static String secret = "Oep2qRedMGonqKGV4ve7fg6q2CUx04uKrebW9COdRKw";
    //意向合同审批流模版ID
    private String templateId = "3TmBHTiwzq6UXaSD1NiZSnkjnZ41xpDkTmjLU9Qw";

    private final static String token = "DAaUxK_HjskzcKE5lq9SFWHI4PgwfiCQhH7bOX8R2zLlSGK9Tx-8B5bTGG1LX8lAT5HqYB0Dxv6LqU1XliBNUBAgHQFy_-sQ0SY_kjBR_wptRuJewTIfZWyidw-AGeTnFEAanAt43vyEYSVGv9-fmvq_iHVI2CyAHgDNgNfKLSbaDcaJKwYOcVvUX0ZutXVaMGCkwEClO74amStMWUmqfw";

    @Test
    public void testToken() {
        //获取access_token
        String accessToken = getAccessToken();
        System.out.println(accessToken);
    }

    @Test
    public void testGetTemplateDetail() {
        //获取审批模板详情
        String templateId = "C4Nu6At3HibKTvgQCqGnwBdw5G3tc1mCpPtUFbrRJ";
        String templateDetail = getTemplateDetail(templateId);
        System.out.println(templateDetail);
    }

    @Test
    public void testGetUserDetail() {
        //获取用户详情
        String userId = "cab";
        WxUserResult res = getUserDetail(userId);
        System.out.println(res);
        System.out.println(res.getUserid());
        System.out.println(res.getName());
        System.out.println(res.getMobile());
        System.out.println(res.getEmail());
        System.out.println("性别。0表示未定义，1表示男性，2表示女性: " + res.getGender());
    }

    @Test
    public void testCommitApprovalApply() {
        //提交审批申请
        String creator_userid = "cab";
        String template_id = "3TmBHTiwzq6UXaSD1NiZSnkjnZ41xpDkTmjLU9Qw";
        CommitApprovalApplyParam param = new CommitApprovalApplyParam(creator_userid, template_id);
        //添加审批人
        param.addApprover(2, "ErTui@ZhangSanFeng");
        //审批申请数据
        param.setApplyDataContents(
                param.controlText("Text-1586447955368", "文本1"),
                param.controlText("Text-1586447964627", "文本2"),
                param.controlText("Text-1586447975810", "文本3"),
                //表哥
                param.controlTable("Table-1631951012362",
                        //明细行1
                        param.tableRow(
                                param.controlText("Text-1586447955368", "文本1"),
                                param.controlText("Text-1586447964627", "文本2"),
                                param.controlText("Text-1586447975810", "文本3")
                        ),
                        //明细行2
                        param.tableRow(
                                param.controlText("Text-1586447955368", "文本1"),
                                param.controlText("Text-1586447964627", "文本2"),
                                param.controlText("Text-1586447975810", "文本3")
                        )
                )
        );
        //摘要信息
        param.setSummaryInfo("摘要信息1", "摘要信息2", "摘要信息3");
        //抄送人
        param.setNotifyer("DaWang");
        param.setNotify_type(2);
        System.out.println(JSON.toJSONString(param));
        String sp_no = commitApprovalApply(param);
        System.out.println(sp_no);
    }

    /**
     * 获取access_token
     *
     * @return token
     */
    public String getAccessToken() {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET"
                .replace("ID", id).replace("SECRET", secret);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<AccessTokenResult> responseEntity = restTemplate.getForEntity(url, AccessTokenResult.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            AccessTokenResult ac = responseEntity.getBody();
            if (ac.getErrcode() == 0) {
                return ac.getAccess_token();
            }
            throw new RuntimeException("获取微信token失败：" + ac.getErrmsg());
        }
        throw new RuntimeException("获取微信token请求访问失败");
    }

    /**
     * 获取审批模板详情
     *
     * @param templateId id
     */
    public String getTemplateDetail(String templateId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", token);

        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> reqParam = new HashMap<>();
        reqParam.put("template_id", templateId);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, reqParam, String.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        return "失败";
    }

    /**
     * 提交审批申请
     *
     * @param param 参数
     * @return 编号
     */
    public String commitApprovalApply(CommitApprovalApplyParam param) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/applyevent?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", token);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, param, JSONObject.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            JSONObject body = responseEntity.getBody();
            if (body.getInteger("errcode") == 0) {
                return body.getString("sp_no");
            }
            throw new RuntimeException("提交审批流程失败：" + body.getString("errmsg"));
        }
        throw new RuntimeException("提交审批流程请求访问失败");
    }

    /**
     * 读取成员
     *
     * @param userId userId
     * @return 编号
     */
    public WxUserResult getUserDetail(String userId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID"
                .replace("ACCESS_TOKEN", token).replace("USERID", userId);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<WxUserResult> responseEntity = restTemplate.getForEntity(url, WxUserResult.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            WxUserResult body = responseEntity.getBody();
            if (body.getErrcode() == 0) {
                return body;
            }
            throw new RuntimeException("提交审批流程失败：" + body.getErrmsg());
        }
        throw new RuntimeException("读取成员失败请求访问失败");
    }
}
